package com.bootcamp.javase2.stream;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @program: StreamCode
 * @description: encoding file
 * @author: Keyu Li
 * @create: 2021-09-11 14:34
 **/

public class Encoding {
    public static void main(String[] args) throws IOException {
//        EncodeFIle(new File("Encoding.java"), new File("Encoded.java"));
        decodeFile(new File("Encoded.java"), new File("Decoded.java"));
    }

    public static void EncodeFIle(File encodingFile, File encodedFile) throws IOException {
        // create object
        FileReader freader = new FileReader(encodingFile);
        FileWriter fwriter = new FileWriter(encodedFile);
        // encoding
        int readData;
        while ((readData = freader.read()) != -1) {
            fwriter.write(EncodeChar(readData));
        }
        // close
        freader.close();
        fwriter.close();
    }

    public static void decodeFile(File decodingFile, File decodedFile) throws IOException {
        // create object
        FileReader freader = new FileReader(decodingFile);
        FileWriter fwriter = new FileWriter(decodedFile);
        // encoding
        int readData;
        while ((readData = freader.read()) != -1) {
            fwriter.write(DecodeChar(readData));
        }
        // close
        freader.close();
        fwriter.close();
    }

    private static int DecodeChar(int idata) {
        char data = (char) idata;
        if (data > '0' && data <= '9') return data - 1;
        if (data > 'a' && data <= 'z') return data - 1;
        if (data > 'A' && data <= 'Z') return data - 1;
        if (data == '0') return '9';
        if (data == 'a') return 'z';
        if (data == 'A') return 'Z';
        return idata;
    }


    private static int EncodeChar(int idata) {
        char data = (char) idata;
        if (data >= '0' && data < '9') return data + 1;
        if (data >= 'a' && data < 'z') return data + 1;
        if (data >= 'A' && data < 'Z') return data + 1;
        if (data == '9') return '0';
        if (data == 'z') return 'a';
        if (data == 'Z') return 'A';
        return idata;
    }
}
